<?php
/**
 * Created by PhpStorm.
 * User: yuanluke
 * Date: 4/21/17
 * Time: 14:44
 */

namespace App\Http\Utils\WechatTrait;

use Log;
use ErrorException;

trait QrcodeTrait {

    /**
     * 生成永久带参数二维码
     * @param $param    二维码中包含的参数
     * @param null $storeFname  如果希望保存二维码图片,则填写保存的文件名;如果只是想获取二维码网址,可不传此参数
     * @return string   只传第一个参数时,返回二维码网址;两个参数都传时,返回本地二维码图片绝对路径
     */
    public function generatePermanentQrcode($param, $storePath=null, $storeFname=null) {

        try {
            Log::debug(get_class($this).' '.__FUNCTION__.' '.'start');

            $wechat = app('wechat');
            $qrcodeService = $wechat->qrcode;
            $qrcodeInfo = $qrcodeService->forever($param);
            $ticket = $qrcodeInfo->ticket;
            $qrcodeUrl = $qrcodeService->url($ticket);
            Log::debug('带参数二维码地址: '.$qrcodeUrl);

            $result = null;
            if ($storePath==null) {
                $result = $qrcodeUrl;
            } else {
                //保存二维码图片到指定路径
                $content = file_get_contents($qrcodeUrl);
                $result = sprintf('%s/%s.jpg', $storePath, $storeFname);
                file_put_contents($result, $content);
            }

            Log::debug(get_class($this).' '.__FUNCTION__.' '.'end');
            return $result;
        } catch (ErrorException $ex) {
            Log::error(get_class($this).' exception '.print_r($ex->getMessage(), true));
            throw $ex;
        }


    }

}